(defun picture-beginning-of-motion()
  (interactive)
  (picture-motion-reverse 1)
  (while (and (/= 1 (line-number-at-pos))
	      (looking-at "[^ \t\n]"))
    (picture-motion-reverse 1)
    )
  (when (looking-at "[ \t\n]")
    (picture-motion 1)
    )
  )

(defun picture-end-of-motion()
  (interactive)
  (let ((total-lines (count-lines (point-min) (point-max))))
    (while (and (/= total-lines (line-number-at-pos))
		(looking-at "[^ \t\n]"))
      (picture-motion 1)
      )
    )
  )

(defun picture-return(&optional arg)
  (interactive "P")
  (picture-beginning-of-motion)
  (if (null arg)
      (picture-forward-column (char-width (char-after)))
    (let ((cw (- 3 (char-width (char-after)))))
      (when (= 0 (current-column))
	(mark-paragraph)
	(string-rectangle (region-beginning) (region-end) (make-string cw ? ))
	(when (looking-at "\\( \\|\t\\)*\n")
	  (picture-motion 1)
	  )
	)
      (picture-backward-column cw)
      )
    )
  )

(defun picture-draw-line(&optional arg)
  (interactive "P")
  (while (or (and (null arg) (not (looking-back "  \\|\t")))
	     (and arg (not (looking-at ".[ \t\n]\\|$"))))
    (picture-insert ?| 1)
    )
  )

(defun picture-return-and-line()
  (interactive)
  (picture-return -1)
  (picture-draw-line -1)
  (picture-return -1)
  )

(defun picture-backward-delete-char()
  (interactive)
  (picture-motion-reverse 1)
  (picture-insert ?\u3000 1)
  (picture-motion-reverse 1)
  )

(add-hook 'picture-mode-hook
	  (lambda()
            (setq indent-tabs-mode nil)
	    (picture-movement-down)
	    (define-key picture-mode-map (kbd "C-c C-a") 'picture-beginning-of-motion)
	    (define-key picture-mode-map (kbd "C-c C-e") 'picture-end-of-motion)
	    (define-key picture-mode-map (kbd "C-c C-r") 'picture-return)
	    (define-key picture-mode-map (kbd "C-c C-j") 'picture-return-and-line)
	    (define-key picture-mode-map (kbd "C-c C-l") 'picture-draw-line)
	    (define-key picture-mode-map (kbd "DEL") 'picture-backward-delete-char)
	    ))

(global-set-key (kbd "C-c C-p") 'picture-mode)

